package com.hxd.mall.module.product

import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectActivity
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_isload_baichuan
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_web_url
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.product_skuNo
import com.hxd.mall.constant.HxdConstants.TB_auther_isgo
import com.hxd.mall.constant.HxdConstants.openedProductDetails
import com.hxd.mall.constant.HxdConstantsRouterPath.Common.path_to_webview
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_main_page
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_product_detail_page
import com.hxd.mall.module.MainActivity
import com.hxd.mall.module.common.AutherBean
import com.hxd.mall.module.product.home.bean.ProductUrlBean
import com.hxd.mall.module.product.home.bean.ShareProductBean
import com.hxd.mall.module.product.search.bean.ProductDetailBean
import com.hxd.mall.module.product.search.bean.ProductDetailImageList
import com.hxd.mall.utils.local.*
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getBooleanData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveBooleanData
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.StackManageUtil.closeOtherOnlyActivity
import com.hxd.mall.utils.local.StackManageUtil.removeActivity
import com.hxd.mall.utils.open.*
import com.hxd.threelibrary.baichuan.AlibcClient
import com.hxd.threelibrary.baichuan.AlibcClient.openByUrl
import com.hxd.threelibrary.baichuan.ShoppingUtils.oppentb
import com.hxd.threelibrary.umeng.UmClient.WEIXIN
import com.hxd.threelibrary.umeng.UmClient.shareText
import kotlinx.android.synthetic.main.activity_product_detail_layout.*
import kotlinx.android.synthetic.main.layout_product_teach.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * 商品详情页
 */
@Route(path = path_hxd_product_detail_page)
class ProductDetailActivity : BaseInjectActivity<IProductDetailPresenter>(), IProductDetailView {

    private var mSkuNo: String = ""
    private var mShareBean: ShareProductBean? = null
    private var shareContent: String = ""
    private var mBean: ProductDetailBean? = null
    private var mBuyBean: ProductUrlBean? = null
    /**
     * 区分 分享 和购买授权入口标记
     * 1 分享
     * 2 购买
     */
    private var mTbAutherFlag = -1
    private var mImageList: MutableList<String> = mutableListOf()
    private val imageListAdapter = ProductImageListAdapter()

    override fun attachLayoutRes(): Int = R.layout.activity_product_detail_layout

    override fun initViews() {
        addSetOnClickListener(back, tv_sahre, now_buy, product_home, layout_teach_one, tv_next_product_teach, tv_center_finish, layout_teach_two, layout_product_teach) {
            onClick(it)
        }
        EventBus.getDefault().register(this)

        sendPoint(commodity_detail_page_view)

        //判断是否是第一次启动
        if (!getBooleanData(openedProductDetails)) {
            saveBooleanData(openedProductDetails, true)
            layout_product_teach.visibility = View.VISIBLE
        }
    }

    override fun initData() {
        mSkuNo = intent.getStringExtra(product_skuNo) ?: ""
        mPresenter?.getDetailData(mSkuNo)
    }

    /**
     * 点击事件
     */
    private fun onClick(it: View) {
        when (it) {
            back -> removeActivity(this)
            tv_sahre -> {
                sendPoint(commodity_share_button_click)
                ActivityUtil.jump {
                    mPresenter?.getVersionInfo(mSkuNo)
                }
            }
            now_buy -> {
                sendPoint(commodity_buy_button_click)
                buyProduct()
            }
            product_home -> {
                //商铺首页
                closeOtherOnlyActivity(MainActivity(), path_hxd_main_page)
            }
            layout_teach_one, tv_next_product_teach -> {
                layout_teach_one.visibility = View.GONE
                layout_teach_two.visibility = View.VISIBLE
            }
            layout_teach_two, tv_center_finish -> layout_product_teach.visibility = View.GONE
        }
    }

    fun buyProduct() {
        ActivityUtil.jump {
            mPresenter?.buyProduct(mSkuNo)
        }
    }

    //展示图片
    fun fetchProductImageList(isShow: Boolean) {
        if (isShow) {
            //展示图片
            if (mImageList.isEmpty()) {
                mPresenter?.fetchProductImage(mSkuNo)
            } else {
                imageListAdapter.setNewData(mImageList)
            }
        } else {
            //隐藏图片
            imageListAdapter.setNewData(mutableListOf())
        }
    }

    override fun showData(t: ProductDetailBean?) {
        if (null == t) return
        mBean = t

        showView()
    }

    //分享
    override fun showSharebean(t: ShareProductBean) {
        if (null == t) return
        mShareBean = t
        when (t?.code) {
            0 -> shareContent()
            9008 -> {
                mTbAutherFlag = 1
                showdialog("淘宝授权后下单或分享产品可以 \n获得收益哦", t?.data?.authUrl)
            }
            else -> ToastUtil.showToast(t.msg ?: "")
        }
    }

    override fun getProductUrl(t: ProductUrlBean) {
        if (null == t) return
        mBuyBean = t
        when (t?.code) {
            0 -> showBuyDialog(t?.data)
            9008 -> {
                mTbAutherFlag = 2
                showdialog("淘宝授权后下单或分享产品可以 \n获得收益哦", t?.data?.authUrl)
            }
            else -> ToastUtil.showToast(t.msg ?: "")
        }
    }

    /**
     * 获取图片list
     */
    override fun fetchProductImageList(t: ProductDetailImageList) {
        if (null == t) return
        mImageList.clear()
        mImageList.addAll(t.data.pictureList)
        fetchProductImageList(true)
    }


    private fun showView() {
        mBean?.data?.saveMoney?.run {
            buy_price.text = this
            tv_money.text = this
            buy_price_teach.text = this
        }

        detailPics.initRecyclerView(imageListAdapter)
        //添加默认的Header
        imageListAdapter.addHeaderView(ProductTopView(this).apply {
            reLoad(mBean)
        })
        //刷新列表
//        mImageList.add("https://img.alicdn.com/imgextra/i4/3816165381/O1CN01ZbmFPt1pcXn7Hwloy_!!3816165381.jpg")
        imageListAdapter.setNewData(mImageList)
    }

    override fun onStop() {
        super.onStop()
        //hideLoading()
        layout_loading.visibility = View.GONE
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe
    fun taoBaoAuther(event: AutherBean) {
        if (event.type != -1) return
        if (event.result == true && mTbAutherFlag != -1) {
            when (mTbAutherFlag) {
                1 -> mPresenter?.getVersionInfo(mSkuNo)
                //淘宝授权成功 打开商品领券界面
                2 -> buyProduct()
            }
        }
    }

    //分享和购买时未授权 需要授权
    private fun showdialog(title: String, url: String?) {
        showDetailShareDialog(title, 2) {
            val tburl = url ?: ""
            if (!TB_auther_isgo) {
                ToastUtil.showToast("授权太频繁啦，休息一会儿再试吧")
                return@showDetailShareDialog
            }

            //showLoading()
            //授权操作
            AlibcClient.login { _, flag ->
                if (!flag) {
                    TB_auther_isgo = flag
                    //hideLoading()
                }
                routerNavigation(path_to_webview, mutableMapOf(key_web_url to tburl, key_isload_baichuan to true))
            }
        }
    }

    //分享时（已授权）
    private fun shareContent() {
        mShareBean?.data?.let {
            shareContent = "从这里去┈→淘寶买东西更便宜！\n" +
                    "/:heart${it.title}\n" +
                    "[Packet]淘宝价：¥${it.reservePrice}\n" +
                    "[Packet]券后价：¥${it.discountPrice}\n" +
                    "[Packet]用锦鲤口袋APP下单再返：¥${it.estimatedIncome}\n" +
                    "————————————\n" +
                    "给你我的【锦鲤口袋】邀请码${it.invitationCode}\n" +
                    "戳我下载 ${it.appDownLoadUrl} \n" +
                    "长按这条信息${it.tpwd}" + "打开手机淘♂寳即可购买"
        }
        showDetailShareDialog(shareContent) {
            shareText(this, WEIXIN, shareContent) {
            }
        }
    }

    //购买(已授权)
    private fun showBuyDialog(data: ProductUrlBean.DataBean?) {
        if (data?.jumpUri != null) {
            //延迟3秒跳转到淘宝
            iv_gif.loadGif(R.mipmap.point)
            layout_loading.visibility = View.VISIBLE
            layout_loading.postDelayed({
                /*oppentb(this@ProductDetailActivity, data.jumpUri) { url ->
                    if (!TextUtils.isEmpty(url))
                        routerNavigation(path_to_webview, key_web_url, url)
                }*/
                openByUrl(this,data.jumpUri)
            }, 2000)
        } else {
            ToastUtil.showToast("未获取到正确地址")
        }

    }
}

